$(document).ready(function () {

    $('#addpost .autocomplete').hide();
    $('.subscription-list').hide();

    $loginfield = $('#login table input[type="text"]').val();
    $passfield = $('#login table input[type="password"]').val();

    //IE hack
    if ($.browser.msie)
        $('#wrapper, #header #in, #footer').css('margin-left', $(document).width() / 2 - 500 + 'px');

    $('#search input').focus(function () {
        $(this).val(null);
    });

    $('#search input').blur(function () {
        $(this).val() == '' ? $(this).val('Rechercher') : 1;
    });

    $('#header > #in > ul li a').hover(
		function () {
		    $(this).stop().animate({ 'padding-top': '10px' });
		},
		function () {
		    $(this).stop().animate({ 'padding-top': '0px' });
		}
	);

    /*    $('#addpost textarea').keydown(function (e) {
        

    }
    });*/

    $('#addpost textarea').keypress(function () {
        if ($(this).val().length >= 140)
            $(this).val($(this).val().substr(0, 140));


    });

    $('#addpost textarea').keyup(function (e) {
        if ($(this).val().indexOf('@') == -1) {
            closeAutoComplete();
        }

        if ($(this).val().indexOf('@') > -1) {

            $username = $(this).val().substr($(this).val().lastIndexOf('@') + 1, $(this).val().length + 1);
            if ($username.length < 1) {
                return;

            }
            $.ajax({
                type: "POST",
                url: "Default.aspx/autocomplete",
                data: "{username:'" + $username + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (res) {
                    var html = "<ul>";
                    html += res.d;
                    html += "</ul>";
                    $('#addpost .autocomplete').html(html);
                    $('#addpost .autocomplete').css({ 'margin-top': '45px' });
                    updateAutcompleteEvents();
                    $('#addpost .autocomplete').show();

                }
            });
        }
    });

    $('#subscription-button').click(function () {
        $('.subscription-list').toggle(300);
    });

    $('.twittajax').click(function () {
        var content = $('#addpost textarea').val();        
        if(content.length < 2)
            return;
        $.ajax({
            type: "POST",
            url: "Default.aspx/addTwitt",
            data: "{text:\"" + content + "\"}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                $('.twitts').html(res.d);
                updateTwittEvents();
                $('#addpost textarea').val(null);
                $("#charactersAvailable").html(140);
                $("#charactersAvailable").removeClass("warning");
            }        
        });        
        return false;
    });

    $('#searchResults').hide();
    $('#search input').keyup(function(){
        if($(this).val().length < 2)
        {
            $('#searchResults').hide();
            return false;
        }
        $username = $(this).val();
        $.ajax({
                type: "POST",
                url: "Default.aspx/autocompleteSearch",
                data: "{username:'" + $username + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (res) {
                    if(res.d.length == 0)
                        return;
                    html = res.d;
                    $('#search #searchResults').html(html);
                    $('#searchResults').show();
                }
            });
    });

    $('.subscribeajax').click(function () {
        $link = $(this);
        $userid = $(this).parents('.follow').find('.userid').text();
        $.ajax({
            type: "POST",
            url: "Default.aspx/subscribeTo",
            data: "{user:" + $userid + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                if (res.d == "False"){
                    showFlash('success', 'Vous n\'etes plus abonn&eacute; a cette personne.');
                    $link.html('S\'abonner');
                }
                else {
                    showFlash('success', 'Information : La demande d\'abonnement a ete envoy&eacute;e.');
                    $link.html('Se d&eacute;sabonner');
                }

                
                
            }
        });

        return false;
    });

    $('.acceptrequest').click(function () {
        $request = $(this).parents('li');

        $.ajax({
            type: "POST",
            url: "Default.aspx/acceptRequest",
            data: "{subscriber:" + $(this).attr('userid') + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                if (res.d == "False")
                    showFlash('error', 'Erreur : la souscription n\'a pu etre confirm&eacute;e');
                else {
                    showFlash('success', 'F&eacute;licitations , une nouvelle personne suit maintenant vos Twittits !');
                    $request.hide(300);
                }

            }
        });

    });

    $('.denyrequest').click(function () {
        $request = $(this).parents('li');

        $.ajax({
            type: "POST",
            url: "Default.aspx/denyRequest",
            data: "{subscriber:" + $(this).attr('userid') + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                if (res.d == "False")
                    showFlash('error', 'Erreur : la souscription n\'a pu etre refus&eacute;e');
                else {
                    showFlash('success', 'Vous avez refus&eacute; la demande de souscription');
                     $request.hide(300);
                }

            }
        });

    });

    $('#older').click(function () {


        $.ajax({
            type: "POST",
            url: "Default.aspx/listTwitts",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                $('#leftpan .twitts').html($('#leftpan .twitts').html() + res.d);  
                updateTwittEvents();
            }
        });
        return false;
    });

    $('#private').click(function () {
        $.ajax({
            type: "POST",
            url: "Default.aspx/listPrivateTwitts",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                $('#leftpan .twitts').html(res.d);  
                updateTwittEvents();
            }
        });
        return false;
    });

    $('#public').click(function () {
        $.ajax({
            type: "POST",
            url: "Default.aspx/listPublicTwitts",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                $('#leftpan .twitts').html(res.d);  
                updateTwittEvents();
            }
        });
        return false;
    });

    $('#login table input[type="text"], #login table input[type="password"]').focus(function () {
        if ($(this).val() == $loginfield || $(this).val() == $passfield) {
            $(this).val(null);
        }
    });

    $('#login table input[type="text"]').blur(function () {
        if ($(this).val() == '') {
            $(this).val($loginfield);
        }
    });

    $('#login table input[type="password"]').blur(function () {
        if ($(this).val() == '') {
            $(this).val($passfield);
        }
    });

    $('#login table input[type="submit"]').click(function () {
        document.location.replace('/twitter/index.html');
    });
	
    $('#profile #MainContent_PrivacyCheckBox').hide();
    $('#profile label[for="MainContent_PrivacyCheckBox"]').hide();
	$('#profile #MainContent_NameTextBox').hide();
    $('#profile #MainContent_TwittitTextBox').hide();
    $('#profile #MainContent_MailTextBox').hide();
    $('#profile #MainContent_WebsiteTextBox').hide();
    $('#profile #MainContent_LocalisationTextBox').hide();
    $('#profile #MainContent_AboutTextBox').hide();
    $('#profile #MainContent_SubmitProfileButton').hide();
    $('#MainContent_TwitterConnectionCheckbox').hide();
    $('label[for=MainContent_TwitterConnectionCheckbox]').hide();

    $('#MainContent_ModifyProfileButton').click(function () {
        $('#profile #MainContent_PrivacyCheckBox').show();       
        $('#profile label[for="MainContent_PrivacyCheckBox"]').show();
        $('#profile #MainContent_NameTextBox').show().val($('#profile #MainContent_NameLabel').html());
        $('#profile #MainContent_TwittitTextBox').show().val($('#profile #MainContent_TwittitLabel').html());
        $('#profile #MainContent_MailTextBox').show().val($('#profile #MainContent_MailLabel').html());
        $('#profile #MainContent_WebsiteTextBox').show().val($('#profile #MainContent_WebsiteLabel').html());
        $('#profile #MainContent_LocalisationTextBox').show().val($('#profile #MainContent_LocalisationLabel').html());
        $('#profile #MainContent_AboutTextBox').show().val($('#profile #MainContent_AboutLabel').html());
        $('#profile #MainContent_SubmitProfileButton').show();
         $('#MainContent_TwitterConnectionCheckbox').show();
         $('label[for=MainContent_TwitterConnectionCheckbox]').show();


        $('#profile #MainContent_UserConfirmLabel').hide();
        $('#profile #MainContent_NameLabel').hide();
        $('#profile #MainContent_TwittitLabel').hide();
        $('#profile #MainContent_MailLabel').hide();
        $('#profile #MainContent_WebsiteLabel').hide();
        $('#profile #MainContent_LocalisationLabel').hide();
        $('#MainContent_TwitterConnectionLabel').hide();
        $(this).hide();
        return false;
    });


    $('.test').click(function () {
        $('#notice').stop().animate({ 'right': '-2px' }, 1000, function () {
            setTimeout(function () {
                $('#notice').stop().animate({ 'right': '-315px' }, 1000);
            }, 2000);

        });

        showFlash('success', 'coucou');
    });

    $('.twitts.tags .twitt .author').hover(function(){
            $.ajax({
                type: "POST",
                url: "Tag.aspx/showProfile",
                data: "{id:" + $(this).find('.id').text() + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (res) {
                   $('#rightpan').html(res.d).show(200);

                },
            }); 
        }, 
        function(){
          
        });
    

    /* twitt control */
    updateTwittEvents();
    countCharacters();
});

function updateAutcompleteEvents(){
	$('#addpost .autocomplete ul li').click(function(){
        $('#addpost textarea').val($('#addpost textarea').val().substr(0, $('#addpost textarea').val().lastIndexOf('@')+1));
		$('#addpost textarea').val($('#addpost textarea').val().substr(0,$('#addpost textarea').val().length -1 ) + ('#'+$(this).html()));
		closeAutoComplete();
	});
}

function closeAutoComplete()
{
	$('#addpost .autocomplete').html('');
	$('#addpost .autocomplete').css({'margin-top' : '0px'});
	$('#addpost .autocomplete').hide();
}

function twittPosted()
{

}

function updateTwittEvents()
{
	$('.ctrl').css({'opacity' : '0.1'});
	$('.twitt').hover(
		function(){
			$(this).find('.ctrl').stop().animate({'opacity' : 1}, 200);				
		},
		function(){
			$(this).find('.ctrl').stop().animate({'opacity' : 0.1}, 200);				
		}
	);

	$('.retwitt').click(function () {
        $textarea = $('#addpost textarea').val('RT#' + trim($(this).parents('.twitt:eq(0)').find('.author').text()) + ' : ' + trim($(this).parents('.twitt:eq(0)').find('.content').text()));
    });

    $('.answer').click(function () {
        $textarea = $('#addpost textarea').val('#' + trim($(this).parents('.twitt:eq(0)').find('.author').text()) + ' : ');
    });

    $('.delete').click(function () {
        $link = $(this);
        jConfirm("Voulez vous supprimer ce twittit ?", "Supprimer un message", function (confirm) {
            if (confirm) {
                $.ajax({
                    type: "POST",
                    url: "Default.aspx/deleteTwitt",
                    data: "{twittId:" + $link.attr('twittid') + "}",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (res) {
                        if (res.d == "False")
                            showFlash('error', 'Erreur : le message n\'a pas pu etre supprim&eacute;');
                        else {
                            showFlash('success', 'Twitt supprimme');
                            $link.parents('.twitt:eq(0)').hide(300).remove();
                        }
                    },
                    error:function(){
                        showFlash('error', 'Erreur : le message n\'a pas pu etre supprim&eacute;');
                    },
                });
            }
        });
       
    });

   /* $('.twitt .content').each(function(i,e){
        var reg = /\#\w+\b/g;

        e.innerHTML = e.innerHTML.replace(reg , '<a href="default.aspx?tag=$&">$&</a>');
    });*/
}

function showFlash(flashclass, msg) {
    $('#flash').css('height', '0px');
    $('#flash').html(msg);
    $('#flash').addClass(flashclass);
    $('#flash').css({ padding: '5px 3px'});

    $('#flash').animate({'height' : '20px'}, 800);

    setTimeout(function () {
        $('#flash').hide(800);
        $('#flash').removeClass(flashclass);
        $('#flash').css({ padding: '0px' });

        $('#flash').html('');
    }, 4000);

}

function trim(myString) {
    return myString.replace(/^\s+/g, '').replace(/\s+$/g, '')
}

function countCharacters() {
    $('#addpost textarea').keyup(function(){calculateCharacters(this)});
	$('#addpost textarea').change(function(){calculateCharacters(this)});
}

function calculateCharacters(obj){
	var count = $(obj).val().length;
	var available = 140 - count;
    if (available < 20) {
        $("#charactersAvailable").addClass("warning");
    }
    else {
       $("#charactersAvailable").removeClass("warning");
    } 
    if(available < 0) { available = 0; };
    $("#charactersAvailable").html(available);			
};
